package com.example.demo.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.demo.pojo.Customer;
import com.example.demo.mapper.CustomerMapper;
import com.example.demo.service.CustomerService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.demo.vo.ResultVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.UUID;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author sjy
 * @since 2025-05-25
 */
@Service
public class CustomerServiceImpl extends ServiceImpl<CustomerMapper, Customer> implements CustomerService {
    @Autowired
    private CustomerMapper customerMapper;

    @Override
    public ResultVO<Customer> customerLogin(String phone, String password) {
        //参数校验
        if(phone == null || password == null || phone.equals("") || password.equals("")){
            return ResultVO.fail("手机号或密码不能为空");
        }

        QueryWrapper queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("phone", phone);
        Customer customer = customerMapper.selectOne(queryWrapper);
        if(customer != null){
            if(customer.getState() == 2){
                return ResultVO.fail("该账号未审核，请联系管理员处理");
            }
            if(customer.getState() == 3){
                return ResultVO.fail("该账号已被冻结，请联系管理员处理");
            }
            if(customer.getPassword().equals(password)){
                return ResultVO.success("登录成功", customer);
            }
            return ResultVO.fail("密码错误");
        }
        return ResultVO.fail("账号不存在");
    }

    @Override
    public ResultVO<Customer> customerRegister(Customer customer) {
        // 检查手机号是否已存在
        QueryWrapper<Customer> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("phone", customer.getPhone());
        Customer existingCustomer = customerMapper.selectOne(queryWrapper);
        if (existingCustomer != null) {
            return ResultVO.fail("该手机号已存在");
        }

        // 生成唯一的账号
        String account = "customer_" + UUID.randomUUID().toString().replace("-", "").substring(0, 10);
        customer.setAccount(account);

        // 账号不存在，插入新客户信息
        boolean isSuccess = this.save(customer);
        if (isSuccess) {
            return ResultVO.success("注册成功", customer);
        } else {
            return ResultVO.fail("注册失败");
        }
    }

    @Override
    public ResultVO<IPage<Customer>> customerQuery(String account, String name, String company, Integer state, Integer pageNum, Integer pageSize) {
        pageNum = pageNum == null || pageNum < 1 ? 1 : pageNum;
        pageSize = pageSize == null || pageSize < 1 ? 10 : pageSize;
        Page<Customer> page = new Page<>(pageNum, pageSize);
        QueryWrapper<Customer> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(account)) {
            queryWrapper.eq("account", account);
        }
        if (StringUtils.isNotBlank(name)) {
            queryWrapper.like("name", name);
        }
        if (StringUtils.isNotBlank(company)) {
            queryWrapper.like("company", company);
        }
        if (state != null) {
            queryWrapper.eq("state", state);
        }
        IPage<Customer> customerPage = customerMapper.selectPage(page, queryWrapper);
        String message = customerPage.getRecords().isEmpty() ?
                "未找到匹配客户" : "查询成功";
        return ResultVO.success(message, customerPage);
    }

    @Override
    public ResultVO<Customer> customerUpdateState(Integer id, Integer state) throws Exception{
        if (state < 1 || state > 3) {
            return ResultVO.fail("无效的状态值");
        }
        UpdateWrapper<Customer> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("id", id)
                .set("state", state);
        boolean updated = update(updateWrapper);
        return updated ?
                ResultVO.success("状态更新成功") :
                ResultVO.fail("客户不存在或更新失败");
    }

    @Transactional
    @Override
    public ResultVO<Customer> recharge(Integer customerId, double amount) {
        QueryWrapper<Customer> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", customerId);
        Customer customer = customerMapper.selectOne(queryWrapper);
        if (customer == null) {
            return ResultVO.fail("客户不存在");
        }
        customer.setBalance(customer.getBalance() + amount);
        customerMapper.updateById(customer);
        return ResultVO.success("充值成功", customer);
    }

    //根据用户ID获取余额
    @Override
    public ResultVO<Double> getBalanceById(Integer customerId) {
        if (customerId == null) {
            return ResultVO.fail("用户ID不能为空");
        }
        Customer customer = customerMapper.selectById(customerId);
        if (customer == null) {
            return ResultVO.fail("用户不存在");
        }
        return ResultVO.success("获取余额成功", customer.getBalance());
    }

}
